import {cloneDeep, isEmpty} from 'lodash-es'

export const voTreeToRowList: (data: AuthorityVo[], extraAttr: ExtraAttr) => AuthorityRow[] = (data, extraAttr) => {
	const extraList: AuthorityVoExtra[] = []
	addAttrs(data, extraAttr, extraList)
	const tableData: AuthorityRow[] = []
	treeToArray(extraList, tableData)
	tableData.forEach((row, index) => {
		Reflect.set(row, '_index', index)
	})
	return tableData
}

export const addAttrs: (data: AuthorityVo[], extraAttr: ExtraAttr, container: AuthorityVoExtra[], isChildren?: boolean) => void = (data, extraAttr, container, isChildren = false) => {
	data.forEach((item, index) => {
		const authorityVoExtra: AuthorityVoExtra = cloneDeep(item)
		authorityVoExtra._parent = isChildren ? extraAttr._parent : undefined
		authorityVoExtra._level = extraAttr._level ?? 0
		authorityVoExtra._expand = extraAttr._expand ?? false
		// 表格的handleRowStyle()方法会处理_show的值，这里置空即可
		authorityVoExtra._show = undefined
		authorityVoExtra._checked = false
		authorityVoExtra._indeterminate = false
		if (isChildren) {
			container.splice(index, 1, authorityVoExtra)
		} else {
			container.push(authorityVoExtra)
		}
		if (!isEmpty(item.children)) {
			addAttrs(item.children, {
				_parent: authorityVoExtra,
				_level: (extraAttr._level ?? 0) + 1,
				_expand: extraAttr._expand ?? false
			}, authorityVoExtra.children, true)
		}
	})
}

export const treeToArray: (data: AuthorityVoExtra[], container: AuthorityRow[], isChildren?: boolean) => void = (data, container, isChildren = false) => {
	data.forEach((item, index) => {
		const authorityRow: AuthorityRow = cloneDeep(item)
		if (isChildren) {
			container.splice(index, 1, authorityRow)
		} else {
			container.push(authorityRow)
		}
		if (!isEmpty(item.children)) {
			treeToArray(item.children, authorityRow.children, true)
		}
	})
}
